package com.mingqijia.gassafety.job.job;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mingqijia.gassafety.db.entity.DtuDataStatistics;
import com.mingqijia.gassafety.db.mapper.DtuDataStatisticsMapper;
import com.mingqijia.gassafety.job.service.impl.DtuDataStatisticsServiceImpl;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xhb
 * @version 1.0.0
 * @Description 设备数据统计
 * @createTime
 */
@Configuration
@EnableScheduling
@Slf4j
public class DtuDataStatisticJob {
    @Autowired
    RedisCacheExt redisUtil;

    @Autowired
    DtuDataStatisticsMapper mapper;

    @Autowired
    DtuDataStatisticsServiceImpl service;

    /**
     * 0 0 0 0 * ? 每天0点运行
     */
    @XxlJob("dtuDataStatistic")
    public ReturnT<String> dtuDataStatistic(String param) {
        XxlJobLogger.log("XXLJOB-dtuDataStatistic start...");
        log.info("dtuDataStatistic--start--------");
        String key = Constants.DTU_DATA_STATISTIC;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT);//15分钟超时
            if (acquire) {
                try {
                    log.info("dtuDataStatistic--进入执行器--------");
                    if (execute()) {
                        return ReturnT.SUCCESS;
                    } else {
                        return ReturnT.FAIL;
                    }
                } catch (Exception e) {
                    log.info("dtuDataStatistic-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.info("dtuDataStatistic-error:{}", e);
        }

        log.info("dtuDataStatistic--end--------");
        XxlJobLogger.log("XXLJOB-dtuDataStatistic end...");
        return ReturnT.SUCCESS;
    }

    private boolean execute() {
        // 根据sql查询出所有符合条件的设备
        List<DtuDataStatistics> dtuDataStatistics = mapper.DtuDataStatisticsList();
        log.info("dtuDataStatistics:{}", dtuDataStatistics);
        // 先查询出所有的数据，对比更新
        LambdaQueryWrapper<DtuDataStatistics> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DtuDataStatistics::getIsDeleted, Constants.IS_DELETED_FALSE);
        List<DtuDataStatistics> dtuDataList = mapper.selectList(lambdaQueryWrapper);
        ArrayList<Integer> ids = new ArrayList<>();
        log.info("dtuDataList:{}", dtuDataList);
        // 如果数据库是空的，就直接填
        if (CollectionUtils.isEmpty(dtuDataList)) {
            for (DtuDataStatistics dtuDataStatistic : dtuDataStatistics) {
                dtuDataStatistic.setCreatedAt(new Date());
            }
            return service.saveBatch(dtuDataStatistics);
        }
        // 如果数据库不是空，就需要进行更新操作
        if (CollectionUtils.isNotEmpty(dtuDataList) && CollectionUtils.isNotEmpty(dtuDataStatistics)) {
            for (DtuDataStatistics dataStatistics : dtuDataList) {
                ids.add(dataStatistics.getId());
            }
            for (DtuDataStatistics dtuDataObjectTwo : dtuDataStatistics) {
                dtuDataObjectTwo.setCreatedAt(new Date());
            }
            // 删除全部，然后新增
            mapper.deleteBatchIds(ids);
            return service.saveBatch(dtuDataStatistics);
        }
        return false;
    }
}
